﻿#region Copyright(C) 2018 FI Ltd. All rights reserved.

// ==================================================================================================
// Copyright(C) 2018 FI Ltd. All rights reserved.
//
// SYSTEM NAME	:   FI.Net Application Framework 
// COMPONENT ID :   FI.EntityFramework
// COMPONENT DESC:  
//
// CREATED DATE/BY: 18 Aug 2018 / Tian Mi
//
// REVISION HISTORY:	DATE/BY			SR#/CS/PM#/OTHERS		DESCRIPTION OF CHANGE
// ==================================================================================================

#endregion

using FI.Core.Data;
using FI.Core.Utilities;
using System.Data.Entity;
using System.Transactions;

namespace FI.EntityFramework
{
    /// <summary>
    /// Represents a set of methods for creating instances of a <see cref="DbContext"/>.
    /// </summary>
    public class DbContextFactory
    {
        /// <summary>
        /// Create an <see cref="DbContext"/> instance.
        /// </summary>
        /// <param name="databaseName">The connection string name specified in configuration.</param>
        /// <returns>The <see cref="DbContext"/> instance.</returns>
        public static DbContext Create(string databaseName)
        {
            Guard.EnsureValidDatabaseName(databaseName);

            var currentTransaction = Transaction.Current;
            if (currentTransaction == null)
            {
                return new DbContext(databaseName);
            }

            var database = DatabaseFactories.GetDatabase(databaseName);
            var openConnection = database.GetOpenConnection();
            if (openConnection == null)
            {
                return new DbContext(databaseName);
            }

            return new DbContext(openConnection, false);
        }
    }
}
